package com.rou.im.framework.core.serializer;

import com.rou.im.framework.core.Request;
import com.rou.im.framework.core.RequestVO;
import com.rou.im.framework.core.cmd.CmdMeta;
import com.rou.im.framework.core.cmd.CmdRegistry;
import com.rou.im.framework.core.cmd.DefaultCmdRegistry;
import com.rou.im.framework.core.exception.CommonRuntimeException;
import com.rou.im.framework.core.util.ConvertUtil;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-22 16:03
 */
public class SerializerManager{

    private final CmdRegistry cmdRegistry ;

    public SerializerManager() {
        cmdRegistry = new DefaultCmdRegistry();
    }

    public SerializerManager(CmdRegistry cmdRegistry) {
        this.cmdRegistry = cmdRegistry;
    }

    public byte[] serialize(Object object) {
        return new byte[0];
    }


    public RequestVO deserialize(Request request) {
        CmdMeta cmdMeta = supports(request);
        if(cmdMeta==null){
           throw new CommonRuntimeException("CMD00001",request.getRequestHeaders().getCmdId());
        }
        try {
            return ConvertUtil.byteArrayToVO((byte[]) request.getRequestBody(), cmdMeta.getSerializerClz(), cmdMeta.getDescriptor());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonRuntimeException("SER00001");
        }
    }

    private CmdMeta supports(Request request) {
        return cmdRegistry.get(request.getRequestHeaders().getCmdId());
    }
}
